﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GalaSoft.MvvmLight;
using System.Collections.ObjectModel;
using Medecine.DataAccess.Users;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Medecine.Interface.Main;
using Medecine.Dbo;
using Medecine.Interface.Utils;
using Medecine.Interface.Properties;
using System.Reactive.Linq;

namespace Medecine.Interface.Users
{
	public class UserListViewModel : ViewModelBase
	{
		public UserListViewModel()
		{
			_addUserCommand = new RightCommand(AddUser, ViewModelLocator.MainStatic.CanInvokeCommand);
			_deleteUserCommand = new RightCommand<UserViewModel>(DeleteUser, CanDeleteUser);
		}

		public void GetUserList()
		{
			_userList.Clear();
			using (ServiceUserClient userService = new ServiceUserClient())
			{
				foreach (User user in userService.GetListUser())
				{
					_userList.Add(new UserViewModel(user));
				}
			}
		}

		private readonly ObservableCollection<UserViewModel> _userList = new ObservableCollection<UserViewModel>();
		public ObservableCollection<UserViewModel> UserList { get { return _userList; } }

		#region Add

		private AddUserViewModel _addUserViewModel = null;

		private readonly RightCommand _addUserCommand = null;
		public RightCommand AddUserCommand { get { return _addUserCommand; } }

		private void AddUser()
		{
			_addUserViewModel = new AddUserViewModel();
			Messenger.Default.Send(new GoToViewMessage(ViewName.AddUser, _addUserViewModel, AddUserCompleted));
		}

		private void AddUserCompleted()
		{
			if (_addUserViewModel.Cancelled == false)
			{
				_userList.Add(new UserViewModel(_addUserViewModel.User));
			}
			
			_addUserViewModel.Cleanup();
			_addUserViewModel = null;
		}

		#endregion // Add

		#region Delete

		private readonly RightCommand<UserViewModel> _deleteUserCommand;
		public RightCommand<UserViewModel> DeleteUserCommand { get { return _deleteUserCommand; } }

		private bool CanDeleteUser(UserViewModel user)
		{
			return (user != null) && ViewModelLocator.MainStatic.CanInvokeCommand();
		}

		private void DeleteUser(UserViewModel user)
		{
			using (ServiceUserClient service = new ServiceUserClient())
			{
				Observable.FromAsyncPattern<string, bool>(service.BeginDeleteUser, service.EndDeleteUser)
					.Invoke(user.UserName)
					.ObserveOnDispatcher()
					.Subscribe(
						(b) => DeleteUserCompleted(user, b),
						(e) => Messenger.Default.Send(new ErrorMessage(e.Message)));
			}
		}

		private void DeleteUserCompleted(UserViewModel user, bool result)
		{
			if (result == true)
				UserList.Remove(user);
			else
				Messenger.Default.Send(new ErrorMessage(Resources.DeleteUserError));
		}

		#endregion // Delete
	}
}
